import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 如果已经明确设置了 Authorization header，则不覆盖
    if (!config.headers.Authorization) {
      // 推文管理是管理员功能，优先使用 adminToken
      let token = localStorage.getItem('adminToken')
      if (!token || token.trim() === '') {
        token = localStorage.getItem('doctorToken')
      }
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API请求失败:', error)
    if (error.response) {
      return Promise.reject(error.response.data)
    } else if (error.request) {
      return Promise.reject({ message: '网络请求失败，请检查网络连接' })
    } else {
      return Promise.reject({ message: error.message || '请求失败' })
    }
  }
)

// ==================== 推文管理功能 ====================

// 创建推文
export const createPush = (data) => {
  return api.post('/admin/push/create', data)
}

// 更新推文
export const updatePush = (data) => {
  return api.put('/admin/push/update', data)
}

// 删除推文
export const deletePush = (id) => {
  return api.delete(`/admin/push/delete/${id}`)
}

// 批量删除推文
export const batchDeletePush = (ids) => {
  return api.delete('/admin/push/batch-delete', { data: { ids } })
}

// 发布推文
export const publishPush = (id) => {
  return api.post(`/admin/push/${id}/publish`)
}

// 撤回推文
export const withdrawPush = (id) => {
  return api.post(`/admin/push/${id}/withdraw`)
}

// 分页查询推文
export const getPushPage = (params) => {
  return api.post('/admin/push/page', params)
}

// 获取推文详情
export const getPushDetail = (id) => {
  return api.get(`/admin/push/detail/${id}`)
}

// 获取推文列表
export const getPushList = (params) => {
  return api.get('/admin/push/list', { params })
}

// 上传推文封面
export const uploadPushCover = (file) => {
  const formData = new FormData()
  formData.append('cover', file)
  
  return api.post('/admin/push/uploadCover', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}
